﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using Baosight.Platform.Core.ServiceModel;
using Baosight.Platform.Core.UI.Controls;
using Baosight.Platform.Core.UI;
using Baosight.Platform.Core;
using Baosight.ZNH.ZMCommon;
using Baosight.ZNH.ZMCommon.Validators;
using Baosight.ZNH.ZMCommon.Prompt;
using Telerik.Windows.Controls;

namespace Baosight.ZNH.ZMCL.UI
{
    /// <summary>
    /// 新增隐患信息
    /// </summary>
    /// Title:ZMCL40
    /// Service:ServiceZMCL40
    /// Copyright:Baosight Software LTD.co Copyright (c) 2011
    /// Company:上海宝信软件股份有限公司
    /// Author: 高强
    /// Version: 1.0
    /// History:
    ///       2011-04-11  高强   [创建]
    ///  

    public partial class ZMCL40 : EFViewCmes
    {
        private string keyId;//获得删除记录的主键
        private Boolean firstSelectionAction = true;//页面判断
        private List<EFDataField> dataFields;//区域的对象list

        //操作模式包括新增和更新
        private new OperationMode Mode
        {
            get;
            set;
        }
        //临时存储按钮对象
        private Button TmpBut
        {
            get;
            set;
        }
        //获得输入区域的所有对象list
        private List<EFDataField> DataFields
        {
            get
            {
                if (dataFields == null)
                {
                    dataFields = this.DETAILS.GetChildObjects<EFDataField>(null, true);
                }
                return dataFields;
            }
        }

        /// <summary>
        /// 构造函数初始化
        /// </summary>
        public ZMCL40()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(ZMCL40_Loaded);
        }

        /// <summary>
        /// 画面载入，如果表没有数据则第一次不响应SelectionAction操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ZMCL40_Loaded(object sender, RoutedEventArgs e)
        {
            if (this.recordGrid.EIBlock.GetRowCount() == 0)
            {
                firstSelectionAction = false;
            }
        }

        /// <summary>
        /// 页面初始化操作
        /// </summary>
        /// <param name="initData"></param>
        public override void Initialize(EIInfo initData)
        {
            base.Initialize(initData);
            this.fdRiskDate.Value = DateTime.Today.ToString("yyyy-MM-dd");//获得默认当天日期
            Mode = OperationMode.Insert;
        }

        /// <summary>
        /// 确定按钮操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnConfirmButtonClick(object sender, RoutedEventArgs e)
        {
            Button but = sender as Button;
            but.IsEnabled = false;
            ValidatorManager group = this.GetChildObject<ValidatorManager>(null);
            if (group != null)
            {
                bool result = group.IsValidSucces;
                if (!result)//如果校验有错则给提示信息
                {
                    this.ValidateMessagePopup();
                    but.IsEnabled = true;
                    return;
                }
                else
                {
                    string curDate = this.fdRiskDate.GetDataValue().ToString();
                    if (this.fdDeadlineDate.Value != null)//判断解决日期是否输入合理
                    {
                        if (!this.fdDeadlineDate.Value.ToString().Equals(""))
                        {
                            if (curDate.CompareTo(this.fdDeadlineDate.GetDataValue().ToString()) > 0)
                            {
                                Prompts pop = Prompts.getInstance();
                                pop.SetMsg("解决期限不能小于隐患日期！");
                                pop.Show(6);
                                but.IsEnabled = true;
                                return;
                            }
                        }
                    }
                    //构造EIInfo
                    EIInfo subInfo = new EIInfo();
                    subInfo.AddBlock(EIConstants.ResultBlock).SetColumns(GetColumns());
                    subInfo.Attributes.Add(EIConstants.ServiceNameKey, "ZMCL40");
                    if (Mode == OperationMode.Insert)
                    {
                        subInfo.Attributes.Add(EIConstants.MethodNameKey, "insert");

                    }
                    else if (Mode == OperationMode.Update)
                    {
                        subInfo.Attributes.Add(EIConstants.MethodNameKey, "update");
                        //根据隐患编号是否可用判断记录是否能更新
                        if (this.fdRiskCode.IsEnabled == false)
                        {
                            //如果不可用则证明有隐患编号存在，更新时不验证隐患编号是否重复
                            subInfo.Set("canUpdate", "0");
                        }
                        else
                        {
                            //如果可用则证明给隐患编号有可能被赋值，更新是需要验证是否重复
                            subInfo.Set("canUpdate", "1");
                        }
                    }
                    subInfo.GetBlock(EIConstants.ResultBlock).AddRow(GetRowValues());
                    this.Submit(subInfo, SubmitCompleted);
                    TmpBut = but;
                }
            }
            
        }

        /// <summary>
        /// 确定按钮后的回调函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SubmitCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == 1)
            {
                if (Mode == OperationMode.Insert)
                {
                    this.recordGrid.EIBlock.AddRow(e.EIInfo.GetBlock(EIConstants.ResultBlock).GetRow(0));
                    // 清空新增区域
                    ClearDataField();
                }
                else if (Mode == OperationMode.Update)
                {
                    int _index = this.recordGrid.SelectedIndex;
                    this.recordGrid.Items.RemoveAt(_index);
                    this.recordGrid.EIBlock.SetRow(_index, e.EIInfo.GetBlock(EIConstants.ResultBlock).GetRow(0));
                    this.recordGrid.SelectedIndex = _index;
                    // 清空新增区域
                    ClearDataField();
                }
            }
            else
            {
                this.OnCommitMessagePopup(e.EIInfo);
            }
            if (TmpBut != null)
            {
                TmpBut.IsEnabled = true;
            }
        }

        /// <summary>
        ///获取DataFieldColumns，不带参数的
        /// </summary>
        public  Dictionary<string, EIColumn> GetColumns()
        {
            Dictionary<string, EIColumn> columns = new Dictionary<string, EIColumn>();
            foreach (var _field in DataFields)
            {
                EIColumn onecolumn = new EIColumn();
                onecolumn.Name = _field.eBindingName;
                onecolumn.Desc = _field.eLabel as string;
                columns.Add(_field.eBindingName, onecolumn);
            }
            return columns;
        }

        /// <summary>
        ///获取行的值
        /// </summary>
        public EIRow GetRowValues()
        {
            EIRow row = new EIRow();
            foreach (var _field in DataFields)
            {
                row.Add(_field.eBindingName, _field.Value);
            }
            return row;
        }

        /// <summary>
        /// 绑定值到指定的Block内 
        /// </summary>
        /// <param name="block"></param>
        /// <param name="columnName"></param>
        /// <param name="dataValue"></param>
        private void BindToBlock(EIBlock block, string columnName, object dataValue, EIRow row)
        {
            EIColumn column = new EIColumn();
            column.SetName(columnName);
            row.Add(columnName, dataValue);
            block.AddColumn(column);
        }

        /// <summary>
        /// 清除按钮后的的操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnClearButtonClick(object sender, RoutedEventArgs e)
        {
            this.recordGrid.SelectedItem = null;
            ClearDataField();
        }

        /// <summary>
        /// 删除按钮后的操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            HyperlinkButton hb = (HyperlinkButton)sender;
            object row = hb.DataContext;
            keyId = row.GetType().GetProperty("fdKeyId").GetValue(row, null).ToString();
            EIInfo eiInfo = new EIInfo();
            eiInfo.Attributes.Add(EIConstants.ServiceNameKey, "ZMCL40");
            eiInfo.Attributes.Add(EIConstants.MethodNameKey, "delete");
            EIBlock resultBlock = new EIBlock(EIConstants.ResultBlock);
            EIRow Row = new EIRow();
            BindToBlock(resultBlock, "fdKeyId", keyId, Row);
            resultBlock.AddRow(Row);
            eiInfo.AddBlock(resultBlock);
            this.Submit(eiInfo, SubmitDeleteCompleted);
        }

        /// <summary>
        /// 删除按钮后的回调函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SubmitDeleteCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status != -1)
            {
                for (int i = 0; i < this.recordGrid.EIBlock.GetRowCount(); i++)
                {
                    EIRow row = this.recordGrid.EIBlock.GetRow(i);
                    if (row["fdKeyId"].ToString().Equals(keyId))
                    {
                        this.recordGrid.EIBlock.GetRows().Remove(row);
                        ClearDataField();
                    }
                }
                ClearDataField();
            }
            else
            {
                this.OnCommitMessagePopup(e.EIInfo);
            }
        }

        /// <summary>
        /// 选中表一条记录，在输入区域显示选择记录的值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void recordGrid_SelectionChanged(object sender, SelectionChangeEventArgs e)
        {
            if (firstSelectionAction == true)//第一次进入光标不选中
            {
                this.recordGrid.SelectedItem = null;
                firstSelectionAction = false;
                return;
            }
            if (this.recordGrid.SelectedItem != null)
            {
                Mode = OperationMode.Update;
                var _item = this.recordGrid.SelectedItem;
                foreach (var _field in DataFields)
                {
                    _field.eRegex = null;
                    _field.eValidateErrorPrompt = null;
                    _field.Value = _item.GetType().GetProperty(_field.eBindingName).GetValue(_item, null);
                    if (_field.Name.Equals("fdRiskCode"))
                    {
                        if (!string.IsNullOrEmpty(_field.Value.ToString()))//如果隐患编号有输入则不能修改，否则可以修改
                        {
                            _field.IsEnabled = false;
                        }else
                        {
                            _field.IsEnabled = true;
                        }
                    }
                }
                //展示列表值得时候设置校验为无效
                ValidatorManager group = this.GetChildObject<ValidatorManager>(null);
                if (group != null)
                {
                    group.InValidateAll();
                }
            }
        }

        /// <summary>
        /// 清空查询区里的值
        /// </summary>
        private void ClearDataField()
        {
            Mode = OperationMode.Insert;
            this.recordGrid.SelectedItem = null;
            foreach (var field in DataFields)
            {
                field.eRegex = null;
                field.eValidateErrorPrompt = null;
                field.Validate();
                if (field.Name.Equals("fdRiskCode"))//如果是隐患编号则设为可用并清空数据
                {
                    field.IsEnabled = true;
                    field.SetDataValue("");
                }
                else if (field.Name.Equals("fdRiskDate"))//如果为三违时间则显示当前的时间
                {
                    this.fdRiskDate.Value = DateTime.Now.ToString("HH:mm:ss");
                }
                else
                {
                    field.SetDataValue("");
                }
            }
            //清除列表值得时候设置校验为无效
            ValidatorManager group = this.GetChildObject<ValidatorManager>(null);
            if (group != null)
            {
                group.InValidateAll();
            }
        }
    }
}
